﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using control.Biz;

namespace control.Dal
{
    class DalPhieuNhap
    {
        internal static List<control.Biz.BizPhieuNhap> GetAll()
        {
            Sach_WebDataContext db =DalCommon.SachDB;
            var phs = from pn in db.PhieuNhaps
                      orderby pn.NgayLapPhieu descending
                      select new BizPhieuNhap()
                      {
                          ID = pn.IDPhieuNhap,
                          Ma = pn.MaPN,
                          NgayNhap = (DateTime)pn.NgayLapPhieu,
                          Items=BizChiTietPhieuNhap.GetListByIDPhieu(pn.IDPhieuNhap)
                      };
            return phs.ToList<BizPhieuNhap>();
        }



        internal static int Insert(BizPhieuNhap bizPhieuNhap)
        {
            Sach_WebDataContext db = DalCommon.SachDB;
            PhieuNhap pn = new PhieuNhap()
            {
                MaPN = bizPhieuNhap.Ma,
                NgayLapPhieu = bizPhieuNhap.NgayNhap,
            };
            db.PhieuNhaps.InsertOnSubmit(pn);
            db.SubmitChanges();
            return pn.IDPhieuNhap;
        }

        internal static void Delete(BizPhieuNhap bizPhieuNhap)
        {
            Sach_WebDataContext db = DalCommon.SachDB;
            PhieuNhap pn = db.PhieuNhaps.Single(p => p.IDPhieuNhap == bizPhieuNhap.ID);
            db.PhieuNhaps.DeleteOnSubmit(pn);
            db.SubmitChanges();
        }

        internal static void Update(BizPhieuNhap bizPhieuNhap)
        {
            Sach_WebDataContext db = DalCommon.SachDB;
            PhieuNhap pn = db.PhieuNhaps.Single(p => p.IDPhieuNhap == bizPhieuNhap.ID);
            pn.MaPN = bizPhieuNhap.Ma;
            db.SubmitChanges();
        }

        internal static List<BizPhieuNhap> Find(string p, DateTime FromDateTime, DateTime ToDateTime)
        {
            Sach_WebDataContext db = DalCommon.SachDB;
            var phs = from pn in db.PhieuNhaps
                      where pn.MaPN.Contains(p) 
                      && ((DateTime)pn.NgayLapPhieu).CompareTo(FromDateTime) >= 0
                      && ((DateTime)pn.NgayLapPhieu).CompareTo(ToDateTime) <= 0
                      orderby pn.NgayLapPhieu descending
                      select new BizPhieuNhap()
                      {
                          ID = pn.IDPhieuNhap,
                          Ma = pn.MaPN,
                          NgayNhap = (DateTime)pn.NgayLapPhieu,
                          Items = BizChiTietPhieuNhap.GetListByIDPhieu(pn.IDPhieuNhap)
                      };
            return phs.ToList<BizPhieuNhap>();
        }
    }
}
